package cn.digiwin.wx.qyh.common;

import cn.digiwin.wx.utils.HttpUtil;
import cn.digiwin.wx.utils.TokenUtil;
import cn.e4j.config.WxProperties;
import cn.e4j.core.util.SpringContextHolder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

/**
 * Created by wenchuan.li 2017-8-18.
 */
public class WeixinComm {

    protected static Logger logger = LoggerFactory.getLogger(WeixinComm.class);

    public final static String METHOD_GET = "GET";
    public final static String METHOD_POST = "POST";
    private final static String QIYE_URL = "https://qyapi.weixin.qq.com/cgi-bin";
    /**
     * 多媒体文件下载
     */
    private final static String QY_MEDIA_URL = "https://qyapi.weixin.qq.com/cgi-bin/media";

    private final static WxProperties wxProperties= SpringContextHolder.getBean(WxProperties.class);

    /**
     * 获取多媒体文件下载完整路径
     *
     * @param media_id
     * @return
     */
    public static String getWxMediaURL(String media_id) {
        return QY_MEDIA_URL + "/get?access_token=" + TokenUtil.getWxToken() + "&media_id=" + media_id;
    }

    /**
     * 获取微信地址。
     *
     * @return
     */
    public static String getWxToken() {
        String corpId = wxProperties.getCorpId();
        String secret = wxProperties.getSecret();
        return QIYE_URL + "/gettoken?corpid=" + corpId + "&corpsecret=" + secret;
    }

    /**
     * 获取微信验证地址。
     *
     * @param redirectUrl
     * @return
     * @throws UnsupportedEncodingException
     */
    public static String getWxAuthorize(String redirectUrl) throws UnsupportedEncodingException {
        String corpId = wxProperties.getCorpId();
        String redirect = URLEncoder.encode(redirectUrl, "utf-8");
        String url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + corpId + "&redirect_uri=" + redirect + "&response_type=code&scope=snsapi_base&state=digiwin#wechat_redirect";
        return url;
    }

    /**
     * 根据code获取用户信息。
     *
     * @param code
     * @param code
     * @return
     */
    public static String getWxUserInfo(String code) {
        String accessToken = TokenUtil.getWxToken();
        String url = QIYE_URL + "/user/getuserinfo?access_token=" + accessToken + "&code=" + code;
        return url;
    }

    /**
     * 获取微信 jsapi_ticket url。
     *
     * @return
     */
    public static String getWxJsapiTicketUrl() {
        String accessToken = TokenUtil.getWxToken();
        logger.debug("...accessToken: " + accessToken);
        return "https://qyapi.weixin.qq.com/cgi-bin/get_jsapi_ticket?access_token=" + accessToken + "&type=jsapi";
    }

    /**
     * 根据userid 获取成员信息
     *
     * @param userid
     * @return
     */
    public static String getWxStaff(String userid) {
        String accessToken = TokenUtil.getWxToken();
        String url = QIYE_URL + "/user/get?access_token=" + accessToken + "&userid=" + userid;
        return url;
    }

    /**
     * 发送消息
     * <p>
     * ids 成员ID列表（消息接收者，多个接收者用‘|’分隔，最多支持1000个）。特殊情况：指定为@all，则向该企业应用的全部成员发送
     *
     * @return
     */
    public static void sendMsg(String ids, String msg) {
        try {

            HttpUtil.sendHttpsRequest(QIYE_URL + "/message/send?access_token=" + TokenUtil.getWxToken(),
                    String.format("{\"touser\" : \"%s\",\"toparty\" : \" @all \",\"totag\" : \" @all \",\"msgtype\" : \"text\",\"agentid\" : %s,\"text\" : {\"content\" : \"%s\"},\"safe\":0}",
                            ids,
                            wxProperties.getAgentId(),
                            msg),
                    "POST");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


}
